package cn.apple.imageshow.action;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.google.appengine.api.datastore.Blob;

import cn.apple.imageshow.jpa.JPAUtil;
import cn.apple.imageshow.model.Image;

@SuppressWarnings("serial")
public class ImageUploadServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(ImageUploadServlet.class
			.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException {
		try {
			Long id = null;
			ServletFileUpload upload = new ServletFileUpload();
			resp.setContentType("text/plain");

			FileItemIterator iterator = upload.getItemIterator(req);
			while (iterator.hasNext()) {
				FileItemStream item = iterator.next();
				InputStream stream = item.openStream();

				if (item.isFormField()) {
					log.warning("Got a form field: " + item.getFieldName());
				} else {
				    String name = item.getName();
				    String type = getType(name);
					log.warning("Got an uploaded file: " + item.getFieldName()
							+ ", name = " + name);
					int maxLength = 0;
					int len = 2;
					byte[] bigBuffer = new byte[1024 * 1024];
					byte[] buffer = new byte[1024];
					while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
						System.arraycopy(buffer, 0, bigBuffer, maxLength , len);
						maxLength += len;
					}
					stream.close();
					byte[] realBuffer = Arrays.copyOf(bigBuffer, maxLength);
					Image image = new Image();
					image.setBlob(new Blob(realBuffer));
					image.setName(name);
					image.setType(type);
					JPAUtil.persistObject(image);
					log.info("save image with name " + name);
					id = image.getId();
				}
			}
			String link = "/show?id="+String.valueOf(id);
			resp.sendRedirect(link);
		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}
	
	private String getType(String name) {
		if(name != null && name.length() > 0){
			int pos = name.lastIndexOf(".");
			return name.substring(pos+1);
		}
		return "";
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
}
